package com.announcement.controller;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.announcement.entity.User;
import com.announcement.sevice.UserService;
import com.announcement.util.JavaMail;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	private User OnlineUser;

	@ModelAttribute
	public void checkUser(HttpServletRequest req, HttpServletResponse res,
			Model model) {
		OnlineUser = (User) req.getSession().getAttribute("OnlineUser");
	}

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String test() {

		userService.test();

		System.out.println("usercontroller");

		return "main";

	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest req, Model model) {

		if (OnlineUser != null) {
			model.addAttribute("tip", "你已经登录");
			model.addAttribute("jumpurl",
					"http://localhost:8080/Announcement/user/index");
			return "tip";
		}

		String token = DigestUtils.md5DigestAsHex(req.getSession().getId()
				.getBytes());
		req.getSession().setAttribute("token", token);
		return "login";
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register1(HttpServletRequest req,

	HttpServletResponse res, User user) {
		if (!(user.getCode().equalsIgnoreCase(req.getSession()
				.getAttribute("code").toString()))) { // 忽略验证码大小写
			req.getSession().setAttribute("tip", "验证码不正确");
			return "redirect:/user/register";
		}
		boolean status = userService.register(user);

		System.out.println("usercontroller");
		if (status) {
			return "login";
		} else {
			return "register";
		}
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register2(HttpServletRequest req,

	HttpServletResponse res) {

		return "register";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest req) {

		req.getSession().setAttribute("OnlineUser", null);

		return "redirect:/user/login";
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(HttpServletRequest req,

	HttpServletResponse res) {
		if (OnlineUser == null)
			return "redirect:/user/login";
		return "redirect:/message/showArticleToHome?pageIndex=1";
	}

	/**
	 * 登录主页
	 * 
	 * @param req
	 * @param res
	 * @param user
	 * @param accept_token
	 * @return
	 */
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public String index(HttpServletRequest req,

	HttpServletResponse res, User user,
			@RequestParam("token") String accept_token, Model model) {
		System.out.println(user.getCode()
				+ req.getSession().getAttribute("code").toString());

		if (!(user.getCode().equalsIgnoreCase(req.getSession()
				.getAttribute("code").toString()))) { // 忽略验证码大小写
			req.getSession().setAttribute("tip", "验证码不正确");
			return "redirect:/user/login";
		} else {

			String token = DigestUtils.md5DigestAsHex(req.getSession().getId()
					.getBytes());
			System.out.println(token + accept_token);

			if (token == null) {
				req.getSession().setAttribute("tip", "你已经提交表单");
				return "redirect:/user/login";
			}

			if (token.equals(accept_token)) {
				User result = userService.verifyUser(user);
				req.getSession().setAttribute("token", null);
				System.out.println("usercontroller");
				if (result != null) {
					req.getSession().setAttribute("OnlineUser", result);
					
					/**
					 * 第一次登陆   转  上传  头像
					 */
					if (result.getUserlogo() == null)
						return "uploadface";
					return "redirect:/message/showArticleToHome?pageIndex=1";
				} else {
					model.addAttribute("tip", "用户名或密码错误");
					this.login(req, model);
					return "login";
				}
			}
			req.getSession().setAttribute("tip", "请退出再登录");
			System.out.println("请退出再登录");
			return "redirect:/user/login";
		}
	}

	@RequestMapping(value = "/toHome", method = RequestMethod.GET)
	public String toHome(HttpServletRequest req, HttpServletResponse res) {
		if (OnlineUser == null)
			return "redirect:/user/login";
		return "myhome";
	}

	@RequestMapping(value = "/forget_password")
	@ResponseBody
	public Map<String, String> forgetPass(HttpServletRequest req, String email) {
		User user = userService.findUserByName(email);
		HashMap<String, String> map = new HashMap<String, String>();
		String tip = "";
		if (user == null) { // 用户名不存在
			tip = "邮箱不存在,你不会忘记了吧?";
			map.put("tip", tip);
			return map;
		}
		try {

			String secretKey = DigestUtils.md5DigestAsHex(req.getSession()
					.getId().getBytes()); // 密钥 Timestamp

			System.out.println("secretKey:" + secretKey);
			Date outDate = new Timestamp(
					System.currentTimeMillis() + 5 * 60 * 1000);// 30分钟后过期
			/*
			 * long date = outDate.getTime() / 1000 * 1000;// 忽略毫秒数
			 */
			user.setCode(secretKey);
			user.setRegisterDate(outDate);
			System.out.println(outDate);
			userService.updateUser(user);// 保存到数据库
			/* String key = user.getEmail() + "$" + date + "$" + secretKey; */

			String emailTitle = "blog 密码找回";
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName()
					+ ":" + req.getServerPort() + path + "/";
			String resetPassHref = basePath + "user/reset_password?key="
					+ secretKey + "&email=" + user.getEmail();
			String emailContent = "您的登陆信息： Email：" + user.getEmail() + ";<br/><a href="
					+ resetPassHref
					+ " target='_BLANK'>点击我重新设置密码</a>"
					+ "<br/>tips:本邮件超过30分钟,链接将会失效，需要重新申请'找回密码'";
			System.out.print(resetPassHref);

			JavaMail.sendMail(emailTitle, emailContent, user.getEmail());
			tip = "操作成功,已经发送找回密码链接到您邮箱。请在30分钟内重置密码";
			/* logInfo(req, email, "申请找回密码"); */
		} catch (Exception e) {
			e.printStackTrace();
			tip = "邮箱不存在？未知错误,联系管理员吧。";
		}
		map.put("tip", tip);
		return map;
	}

	@RequestMapping(value = "/reset_password", method = RequestMethod.GET)
	public ModelAndView checkResetLink(String key, String email,
			HttpServletRequest req) {
		ModelAndView model = new ModelAndView("tip");
		String tip = "";
		if (key.equals("") || email.equals("")) {
			tip = "链接不完整,请重新生成";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		User user = userService.findUserByName(email);
		if (user == null) {
			tip = "链接错误,无法找到匹配用户,请重新申请找回密码.";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		Date outDate = user.getRegisterDate();
		if (outDate.getTime() <= System.currentTimeMillis()) { // 表示已经过期
			tip = "链接已经过期,请重新申请找回密码.";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		if (!user.getCode().equals(key)) {
			tip = "链接不正确,Code不正确了?重新申请吧";
			model.addObject("tip", tip);
			System.out.println(tip);
			return model;
		}
		model.setViewName("resetpwd"); // 返回到修改密码的界面
		model.addObject("email", email);
		model.addObject("code", key);
		return model;
	}

	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public String updateUser(String email, String pwd) {
		User user = userService.findUserByName(email);
		user.setPassword(pwd);
		userService.updateUser(user);
		return "redirect:/user/login";
	}

	@RequestMapping(value = "/vertifyEmail", method = RequestMethod.POST)
	public void vertify(String email, HttpServletResponse req)
			throws IOException {

		System.out.println("AJAX");
		User user = userService.findUserByName(email);
		if (user != null) {
			req.getWriter().printf("{\"success\":true }");
		} else {
			req.getWriter().printf("{\"success\":false}");
		}
	}

}
